<template>
  <div>
    <Card>
      <Button type="primary" @click="addData" :disabled="allData.length === 1"
        >新增</Button
      >
      <div style="margin-top:20px">
        <Table :columns="columns" :data="allData">
          <template slot-scope="{ row, index }" slot="action">
            <a style="margin-right: 5px" @click="editData(row)">编辑</a>
            <Divider type="vertical" />
            <a @click="deleteData(row)">删除</a>
          </template>
          <template slot-scope="{ row, index }" slot="timeArr">
            <span>{{ row.start_time }}</span>
            <span> - </span>
            <span>{{ row.end_time }}</span>
          </template>
          <template slot-scope="{ row, index }" slot="delay_time_arr">
            <span v-for="(item, index) in row.delay_time_arr" :key="index">
              <span>{{ item }}秒</span>
              <span v-if="index !== row.delay_time_arr.length - 1">，</span>
            </span>
          </template>
          <template slot-scope="{ row, index }" slot="created_at">
            <span>
              {{ row.created_at.substring(0, row.created_at.length - 3) }}
            </span>
          </template>
          <template slot-scope="{ row, index }" slot="wechatno">
            <Tooltip
              max-width="300"
              placement="bottom-start"
              :content="
                row.wechatnick + '(' + (row.wechatno || row.wechatid) + ')'
              "
            >
              {{ row.wechatnick }} ({{ row.wechatno || row.wechatid }})
            </Tooltip>
          </template>
        </Table>
      </div>
      <!-- <div class="ivu-mt ivu-text-center">
        <Page show-total show-elevator show-sizer :total="total" :current.sync="pageParams.page"
          :page-size="pageParams.pageSize" :page-size-opts="pageOpts" @on-change="changePageSize"
          @on-page-size-change="formChangePage" />;''
      </div> -->
      <Modal
        v-model="modal"
        :title="modalStatus"
        :mask-closable="false"
        @on-cancel="cancel"
        width="600"
      >
        <Form :rules="rules" ref="formBox" :model="formBox" :label-width="80">
          <FormItem prop="wxContent" label="微信号：">
            <Select v-model="formBox.wxContent" style="width:200px">
              <Option v-for="item in wxList" :value="item.id" :key="item.id"
                >{{ item.wechatno || item.wechatid }}
              </Option>
            </Select>
          </FormItem>
          <FormItem prop="timeArr" label="时间段：">
            <TimePicker
              format="HH:mm"
              ref="timePick"
              v-model="formBox.timeArr"
              confirm
              type="timerange"
              placement="bottom-end"
              placeholder="请选择"
              style="width: 168px"
            >
            </TimePicker>
          </FormItem>
          <FormItem label="话术:">
            <div
              v-for="(item, index) in formBox.content"
              :key="index"
              class="mtArr"
              v-if="item.status === 1"
            >
              <Row>
                <Col span="10">
                  <FormItem
                    :rules="{
                      required: true,
                      message: '请完善',
                      trigger: 'blur',
                    }"
                    :prop="'content.' + index + '.one'"
                    :key="index"
                  >
                    <Input v-model="item.one" />
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem
                    :label-width="90"
                    label="间隔时间:"
                    :rules="{
                      required: true,
                      message: '请完善',
                      trigger: 'blur',
                    }"
                    :prop="'content.' + index + '.two'"
                    :key="index"
                  >
                    <span style="display: flex;">
                      <Input v-width="60" v-model="item.two"></Input>
                      <span style="margin-left: 10px;">
                        秒
                      </span>
                    </span>
                  </FormItem>
                </Col>
                <Col span="4">
                  <Button
                    v-if="index !== 0"
                    style="margin-left: 20px;"
                    @click="deleteOne(index)"
                    >删除</Button
                  >
                </Col>
              </Row>
            </div>
          </FormItem>
          <FormItem>
            <Button style="margin-top: 10px;" @click="addContent"
              >+ 新增话术</Button
            >
          </FormItem>
        </Form>
        <div slot="footer">
          <Button @click="cancel">取消</Button>
          <Button type="primary" :loading="subLoading" @click="submitParams"
            >确定</Button
          >
        </div>
      </Modal>
    </Card>
  </div>
</template>
<script>
import {
  robotWeList,
  setEInfo,
  addRoborEchat,
  deleteRoborEchat,
  editRoborEchat,
} from "@api/TApi";
export default {
  name: "eSet",
  data() {
    const validateTime = (rule, value, callback) => {
      if (value[1] && value[0]) {
        callback();
      } else {
        callback(new Error("请选择"));
      }
    };
    const validateWxContent = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback(new Error("请选择"));
      }
    };
    return {
      rules: {
        wxContent: [{ validator: validateWxContent, trigger: "change" }],
        timeArr: [{ validator: validateTime, trigger: "change" }],
      },
      total: 0,
      wxList: [],
      subLoading: false,
      pageOpts: [10, 15, 20, 30, 50], // 分页每页数量
      modalStatus: "",
      modal: false,
      formBox: {
        wxContent: "",
        timeArr: [],
        content: [
          {
            one: null,
            two: null,
            status: 1,
          },
        ],
      },
      pageParams: {
        page: 1,
        pageSize: 10,
      },
      columns: [
        {
          title: "微信号",
          slot: "wechatno",
          tooltip: true,
          ellipsis: true,
          width: 250,
        },
        {
          title: "时间段",
          slot: "timeArr",
        },
        {
          title: "话术条数",
          key: "content_num",
        },
        {
          title: "间隔时间",
          slot: "delay_time_arr",
        },
        {
          title: "创建时间",
          slot: "created_at",
        },
        {
          title: "操作",
          slot: "action",
          width: 150,
          align: "center",
        },
      ],
      allData: [],
    };
  },
  methods: {
    deleteData(row) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "<p>是否确认删除，删除后无法恢复</p>",
        onOk: () => {
          deleteRoborEchat({ id: row.id }).then((res) => {
            this.$Message.success("删除成功");
            this._robotWeList();
          });
        },
      });
    },
    submitParams() {
      this.$refs.formBox.validate((valid) => {
        if (valid) {
          let content_json = this.formBox.content
            .filter((ee) => ee.status === 1)
            .map((ee) => {
              return {
                content: ee.one,
                delay_time: ee.two,
              };
            });
          let params = {
            robot_id: this.formBox.wxContent,
            start_time: this.formBox.timeArr[0],
            end_time: this.formBox.timeArr[1],
            content_json: JSON.stringify(content_json),
          };
          let messages = "新增成功";
          let fn = addRoborEchat;
          if (this.modalStatus === "编辑") {
            params.id = this.isEditId;
            fn = editRoborEchat;
            messages = "编辑成功";
          }
          this.subLoading = true;
          fn(params)
            .then((res) => {
              this.$Message.success(messages);
              this.cancel();
              this._robotWeList();
            })
            .finally(() => {
              this.subLoading = false;
            });
        }
      });
    },
    deleteOne(index) {
      this.formBox.content[index].status = 0;
    },
    addContent() {
      this.formBox.content.push({
        one: null,
        two: null,
        status: 1,
      });
    },
    editData(row) {
      this.isEditId = row.id;
      setEInfo({ id: row.id }).then((res) => {
        this.modalStatus = "编辑";
        this.wxList = res.condition.wechat_list;
        this.formBox.wxContent = String(res.robot_id);
        this.formBox.timeArr = [res.start_time, res.end_time];
        this.formBox.content = res.content_list.map((ee) => {
          return {
            one: ee.content,
            two: ee.delay_time,
            status: 1,
          };
        });
        this.modal = true;
      });
    },
    addData() {
      this.modalStatus = "新增";
      setEInfo({ id: 0 }).then((res) => {
        this.wxList = res.condition.wechat_list;
        this.modal = true;
      });
    },
    cancel() {
      this.modal = false;
      this.$refs.formBox.resetFields();
      this.formBox.content = [
        {
          one: null,
          two: null,
          status: 1,
        },
      ];
    },
    changePageSize(e) {
      this.pageParams.page = e;
      this._robotWeList();
    },
    /* @函数功能: 每页数量 */
    formChangePage(e) {
      this.pageParams.pageSize = e;
      this._robotWeList();
    },
    _robotWeList() {
      robotWeList().then((res) => {
        this.allData = res.list;
        this.total = res.total.map;
      });
    },
  },
  mounted() {},
  created() {
    this._robotWeList();
  },
};
</script>
<style lang="less" scoped>
.mtArr:not(:first-child) {
  margin-top: 25px;
}
</style>
